﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Sys.Controls
{
    public class Pager : WebControl
    {
        protected override void Render(HtmlTextWriter wt)
        {
            wt.Write(CreateHtml());
        }

        public int recordcount { get; set; }

        public int rows { get; set; }

        public int page { get; set; }

        public string url { get; set; }

        public string other { get; set; }

        public string CreateHtml()
        {
            StringBuilder sb = new StringBuilder();

            int totalPage = 0;

            if (rows == 0) { return string.Empty; }
            if (recordcount == 0) { return string.Empty; }

            if (recordcount % rows != 0) { totalPage = recordcount / rows + 1; }
            else { totalPage = recordcount / rows; }

            if (page == 0) { page = 1; }

            sb.Append("<span>");

            for (int i = 1; i <= totalPage; i++)
            {
                if (i == 2 && page - 4 > 1)
                {
                    sb.Append("<a href='javascript:void(0)' class='page_01'>...</a>");
                    i = page - 4;
                }
                else if (i == page + 4 && page + 4 < totalPage)
                {
                    sb.Append("<a href='javascript:void(0)' class='page_01'>...</a>");
                    i = totalPage - 1;
                }
                else
                {
                    if (page == i)
                    {
                        sb.Append("<a href='javascript:void(0)' class='page_02'>" + page + "</a>");
                    }
                    else
                    {
                        sb.Append("<a href='" + url + "?page=" + i + other + "' class='page_01'>" + i + "</a>");
                    }
                }
            }

            sb.Append("</span>");
            sb.Append("<em>共<strong> " + totalPage + " </strong>页");
            sb.Append("<strong> " + recordcount + " </strong>条记录</em>");

            return "<div class='page'>" + sb.ToString() + "</div>";
        }

        public void UpdatePage(int recordcount, int rows, int page, string url, string other)
        {
            this.recordcount = recordcount;
            this.rows = rows;
            this.page = page;
            this.url = url;
            this.other = other;
        }
    }
}
